package by.alex.dzeshko.facebooksuperclient;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import by.alex.dzeshko.facebooksuperclient.adapter.CommentsAdapter;
import by.alex.dzeshko.facebooksuperclient.api.ApiRequest;
import by.alex.dzeshko.facebooksuperclient.async.LoadJsonObjectAsyncTask;
import by.alex.dzeshko.facebooksuperclient.async.common.ParamCallback;
import by.alex.dzeshko.facebooksuperclient.constants.FbConstants;
import by.alex.dzeshko.facebooksuperclient.database.DbNewsfeedHelper;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder.Type;
import by.alex.dzeshko.facebooksuperclient.image.ImageLoader;
import by.alex.dzeshko.facebooksuperclient.oauth.FBOAuthHelper;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import by.alex.dzeshko.facebooksuperclient.service.PostService;
import by.alex.dzeshko.facebooksuperclient.utils.FbPictureManager;
import by.alex.dzeshko.facebooksuperclient.utils.InetChecker;

public class FeedItemActivity extends FragmentActivity {
	
	private static final String NEXT = "next";

	private static final String DATA = "data";

	private static final String PAGING = "paging";

	protected static final String LOG_TAG = "FeedItemActivity";

	private static final int NO_DATA = -1;

	private String mPostOwnerId, mItemId, mObjectId, mContentImageUrl;
	
	private static String mAppUserId;

	private TextView mTextViewName, mTextViewStory, mTextViewCreatedTime, mTextViewMessage, 
						mTextViewLikesCount, mTextViewCaption, mTextViewCommentCount;
	
	private ListView mListView;

	private ImageView mImageViewPosterImage, mImageViewContentImage;
	
	private EditText mEditTextNewComment;
	
	private ImageButton mButtonDel,	mButtonLike, mButtonShare, mButtonComment;
	
	private LinearLayout mViewEditCommentBar, mViewBtnBotomBar;
	
	private ProgressBar pbComments;

	private DbNewsfeedHelper mDbHelper;

	private Cursor mCursor;

	private BroadcastReceiver mHttpServiceReceiver;

	private View mViewNewsDetails, mViewLoading;
	
	private CommentsAdapter mCommentsAdapter;

	private InputMethodManager mKeyboard;

	private List<JSONObject> mData;
	
	private Boolean mIsLoading;
	
	private String mNextPageUrl, mFeedType;
 	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_feed_item);
		mKeyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		Intent recievedIntent = getIntent();
		mFeedType = recievedIntent.getStringExtra(FbConstants.FEED_TYPE);
		mItemId = recievedIntent.getStringExtra(FbConstants.ITEM_ID);
		mPostOwnerId = recievedIntent.getStringExtra(FbConstants.USER_ID);
		mObjectId = mPostOwnerId+"_"+mItemId;
		pbComments = (ProgressBar) findViewById(R.id.pbCommentsLoading);
		pbComments.setVisibility(View.GONE);
		loadComments(ApiRequest.getCommentApiUrl(mObjectId));

		mViewNewsDetails = getLayoutInflater().inflate(R.layout.view_header_feed_item_details, null);
		mViewLoading = getLayoutInflater().inflate(R.layout.view_listitem_loading, null);
		mTextViewMessage = (TextView) mViewNewsDetails.findViewById(R.id.tvPostMessage);
		mTextViewLikesCount = (TextView) mViewNewsDetails.findViewById(R.id.tvCommentCount);
		mTextViewCommentCount = (TextView) mViewNewsDetails.findViewById(R.id.tvLikeCount);
		mTextViewCaption = (TextView) mViewNewsDetails.findViewById(R.id.tvPostCaption);
		mTextViewStory = (TextView) mViewNewsDetails.findViewById(R.id.tvPostStory);
		mImageViewContentImage = (ImageView) mViewNewsDetails.findViewById(R.id.ivContentImage);
		android.view.View.OnClickListener listener = new android.view.View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				if(!TextUtils.isEmpty(mContentImageUrl)){
					Intent picture = new Intent(FeedItemActivity.this, ImageActivity.class);
					picture.putExtra(FbConstants.URL, mContentImageUrl);
					startActivity(picture);
				}
			}
		};
		mImageViewContentImage.setOnClickListener(listener);

		mTextViewName = (TextView) findViewById(R.id.tvPosterName);
		mImageViewPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
		mTextViewCreatedTime = (TextView) findViewById(R.id.tvPostedAt);
		mListView = (ListView) findViewById(R.id.lvFeedItem);
		mButtonLike = (ImageButton) findViewById(R.id.btnLikePost);
		mButtonShare = (ImageButton) findViewById(R.id.btnSharePost);
		mButtonShare.setVisibility(View.GONE);
		mButtonDel = (ImageButton) findViewById(R.id.btnDeletePost);
		mButtonComment = (ImageButton) findViewById(R.id.btnCommentPost);
		mEditTextNewComment = (EditText) findViewById(R.id.etNewComment);
		mViewBtnBotomBar = (LinearLayout) findViewById(R.id.llBtnBotomBar);
		mViewEditCommentBar = (LinearLayout) findViewById(R.id.llEditCommentBar);

		mListView.addHeaderView(mViewNewsDetails);
		mListView.addFooterView(mViewLoading);
		mData = new ArrayList<JSONObject>();
		mCommentsAdapter = new CommentsAdapter(getApplicationContext(), R.layout.adapter_comments, mData);
		mListView.setAdapter(mCommentsAdapter);
		SharedPreferences prefs = getSharedPreferences(FBOAuthHelper.AUTH_PREFS, MODE_PRIVATE);
		mAppUserId = prefs.getString(FBOAuthHelper.USER_ID, null);
		
		if(!mPostOwnerId.equals(mAppUserId)) {
			mButtonDel.setEnabled(false);
			mButtonDel.setVisibility(View.GONE);
		}
		
		bindViews(mFeedType);
		
		mHttpServiceReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {

				String action = intent.getAction();
				if (action.equals(PostService.ACTION_ON_ERROR)) {
					Toast.makeText(FeedItemActivity.this,intent.getStringExtra(PostService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
				} else if (action.equals(PostService.ACTION_ON_SUCCESS)) {
					Toast.makeText(FeedItemActivity.this, "Sended",	Toast.LENGTH_SHORT).show();
				} else if (action.equals(PostService.POST_ON_SUCCESS)) {
					loadComments(ApiRequest.getCommentApiUrl(mObjectId));
					Toast.makeText(FeedItemActivity.this, "Posted",	Toast.LENGTH_SHORT).show();
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(PostService.ACTION_ON_ERROR);
		filter.addAction(PostService.ACTION_ON_SUCCESS);
		filter.addAction(PostService.POST_ON_SUCCESS);
		registerReceiver(mHttpServiceReceiver, filter);
		mListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {	}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				
				if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount + 2 >= totalItemCount && mNextPageUrl!=null) {
					if(!mIsLoading){
						loadComments(mNextPageUrl);
					}
				}
			}

		});
	}
	
	private void loadComments(String url) {
		if(!InetChecker.checkInetConnection(this)){
			mIsLoading = false;
			return;
		}
		mIsLoading=true;
		RequestBuilder request = new RequestBuilder();
		request.setType(Type.GET);
		request.setUrl(url);
		new LoadJsonObjectAsyncTask(new ParamCallback<JSONObject>() {

			@Override
			public void onSuccess(JSONObject obj) {
				
				try {
					JSONArray array = obj.getJSONArray(DATA);
					for (int i = 0; i < array.length(); i++) {
						mData.add(array.getJSONObject(i));
					}
					mNextPageUrl = null;
					if(obj.has(PAGING)){
						JSONObject paging = obj.getJSONObject(PAGING);
						if(paging.has(NEXT)){
							mNextPageUrl = paging.getString(NEXT);
							Log.d(LOG_TAG, "comms paging next"+ mNextPageUrl);
						}
					}
					mCommentsAdapter.notifyDataSetChanged();
					if(mNextPageUrl==null && mListView.getFooterViewsCount()>0){
						mListView.removeFooterView(mViewLoading);
					}
				} catch (JSONException e) {
					Log.e(LOG_TAG, e.toString());
				}
				mIsLoading = false;
			}
			
			@Override
			public void onError(Throwable e) {
				Log.e(LOG_TAG, e.toString());
			}
		}).start(request);
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mHttpServiceReceiver);
	}
	
	public void bindViews(String feedMarker) {
		mDbHelper = new DbNewsfeedHelper(this, null);
		mCursor = mDbHelper.getItems(feedMarker);
		if(mCursor.moveToFirst()){
			do{
				if(mCursor.getString(mCursor.getColumnIndex(FbContract.FeedColumns.ITEM_ID)).equals(mItemId)){	
				setViewDetailsValues(mCursor);
				mDbHelper.close();
				return;
				}
			}
			while(mCursor.moveToNext());
		}
	}

	private void hideButtons(){
		mButtonComment.setVisibility(View.GONE);
		mButtonLike.setVisibility(View.GONE);
		mButtonDel.setVisibility(View.GONE);
		mButtonShare.setVisibility(View.GONE);
	}
	
	private void setViewDetailsValues(Cursor cursor) {
		int c = cursor.getInt(cursor.getColumnIndex(FbContract.FeedColumns.COMMENT_LINK));
		int l = cursor.getInt(cursor.getColumnIndex(FbContract.FeedColumns.LIKE_LINK));
		if(l == NO_DATA || c == NO_DATA){hideButtons();}
		String name = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.FROM_NAME));
		mTextViewName.setText(name);
		String time = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.CREATED_TIME));
		String[] datetime = time.split("T");
		time = datetime[1].substring(0,datetime[1].indexOf("+"));
		mTextViewCreatedTime.setText(datetime[0]+" at "+time);
		String story = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.STORY));
		mTextViewStory.setText(story);
		mTextViewMessage.setText(cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.MESSAGE)));
		mTextViewLikesCount.setText(cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.LIKES_COUNT)));
		mTextViewCommentCount.setText(cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.COMMENTS_COUNT)));
		mTextViewCaption.setText(cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.CAPTION)));
		Linkify.addLinks(mTextViewMessage, Linkify.WEB_URLS);
		Linkify.addLinks(mTextViewCaption, Linkify.WEB_URLS);
		ImageLoader loader =  ImageLoader.getInstance();
		mContentImageUrl = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.CONTENT_PICTURE));
		if(!TextUtils.isEmpty(mContentImageUrl)){
			String url = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.CONTENT_PICTURE));
			url = FbPictureManager.getMediumPictureUrl(url);
			mImageViewContentImage.setImageResource(android.R.drawable.ic_menu_gallery);
			loader.bind(mImageViewContentImage, url);
		}
		String url = cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.USER_PICTURE_URL));
		if(!TextUtils.isEmpty(url)){
			mImageViewPosterImage.setImageBitmap(null);
			loader.bind(mImageViewPosterImage, url);
		}
	}
	
	public void onDeleteClick(View v){
		
		AlertDialog.Builder dialog_builder = new AlertDialog.Builder(this);
		dialog_builder.setTitle("Delete?")
					.setMessage("Do you really want to delete?")
					.setIcon(android.R.drawable.ic_menu_delete)
					.setPositiveButton("Sure", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(FBOAuthHelper.getToken()==null){
					return;
				}
				else{
					Intent intent = new Intent(FeedItemActivity.this, PostService.class);
					String url = ApiRequest.getBasicApiUrl(mObjectId);
					url=ApiRequest.addToken(url);
					RequestBuilder requestBuilder = new RequestBuilder();
					requestBuilder.setType(RequestBuilder.Type.DELETE);
					requestBuilder.setUrl(url);
					intent.putExtra(PostService.HTTP_REQUEST_BUILDER, requestBuilder);
					startService(intent);
					
					mDbHelper = new DbNewsfeedHelper(FeedItemActivity.this, null);
					mDbHelper.deleteItem(mItemId);
					mDbHelper.close();
					
					startActivity(new Intent(FeedItemActivity.this, FeedMainActivity.class));
					finish();
				}
			}
		})
		.setNegativeButton("No", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		}).create().show();	
	}
	
	public void onClickToUserProfile(View v){}
	
	public void onLikeClick(View v){
		
		Intent new_like = new Intent(this, PostService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.POST);
		requestBuilder.setUrl(ApiRequest.getLikeApiUrl(mObjectId));
		new_like.putExtra(PostService.HTTP_REQUEST_BUILDER, requestBuilder);
		startService(new_like);
	}
	
	public void onShareClick(View v){}
	
	public void onCommentClick(View v){
		mViewBtnBotomBar.setVisibility(View.GONE);
		mViewEditCommentBar.setVisibility(View.VISIBLE);
		mEditTextNewComment.requestFocus();
        mKeyboard.showSoftInput(mEditTextNewComment, 0);
	}
	
	public void onSendCommentClick(View v){
		String message = mEditTextNewComment.getText().toString();
		if(message.length()==0)
			return;
		mKeyboard.hideSoftInputFromWindow(mEditTextNewComment.getWindowToken(), 0);
		Intent new_comment = new Intent(this, PostService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.POST);
		requestBuilder.setMessage(message);
		requestBuilder.setUrl(ApiRequest.getCommentApiUrl(mObjectId));
		new_comment.putExtra(PostService.HTTP_REQUEST_BUILDER, requestBuilder);
		startService(new_comment);
		mViewEditCommentBar.setVisibility(View.GONE);
		mViewBtnBotomBar.setVisibility(View.VISIBLE);
	}

}
